/*
 * @@Descripttion: 
 * @@version: 
 * @@encoding: utf-8
 * @@Author: qiurongcan
 * @Date: 2025-09-17 10:09:09
 * @LastEditTime: 2025-09-17 10:39:54
 */
// 最小下降路径


#include<iostream>
#include<vector>
#include<algorithm>


using namespace std;

class Solution{
public:
    int minFallingPathSum(vector<vector<int>> & matrix){
        int m = matrix.size();
        int n = matrix[0].size();
        
        if(m == 1) return matrix[0][0];

        vector<vector<int>> dp(m, vector<int>(n, 0));

        for(int i=0; i < m; i++){
            dp[0][i] = matrix[0][i];
        }

        for(int i = 1; i < m; i++){

            for(int j=0; j < m; j++){
                if(j == 0){
                    dp[i][j] = min(dp[i-1][j], dp[i-1][j + 1]) + matrix[i][j];
                }
                else if (j == m - 1)
                {
                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + matrix[i][j];
                }else{
                    dp[i][j] = min({dp[i-1][j-1], dp[i-1][j], dp[i-1][j + 1]}) + matrix[i][j];
                }
            }

        }

        return *min_element(dp[m-1].begin(), dp[m-1].end());

    }


};



